package com.itheima.controller;

import com.itheima.pojo.Article;
import com.itheima.pojo.Category;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.ArticleService;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 样例接口：文章分类
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleService articleService;
    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category){
        categoryService.add(category);
        return Result.success();
    }
    @GetMapping
    public Result<List<Category>> list(){
        List<Category> list = categoryService.list();
        return Result.success(list);
    }
    @GetMapping("/detail")
    public Result<Category>detail(@RequestParam Integer id){
        Category category = categoryService.detail(id);
        return Result.success(category);
    }
    @PutMapping
    public Result update(@RequestBody @Validated(Category.Update.class) Category category){
        categoryService.update(category);
        return Result.success();
    }
    @DeleteMapping
    public Result delete(@RequestParam Integer id){
        //1.该用户分类下有文章不能删除
        // 由于该分类的id唯一，所以数据库中相关联的artilce表中的categoryId字段值为该id的文章都是该分类下的文章
        // 通过该id查询文章列表，如果有文章则不能删除
        PageBean<Article> listState1 = articleService.list(1, 5, id,"已发布");
        PageBean<Article> listState2 = articleService.list(1, 5, id,"草稿");
        if (!listState1.getItems().isEmpty() || !listState2.getItems().isEmpty()){
            return Result.error("该分类下有文章不能删除");
        }
        //2.分类下没有文章能删除
        categoryService.delete(id);
        return Result.success();
    }
}
